import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common'
import { Response } from 'express'
import { returnPack } from '../constants/config.contants'
import { HttpCodeMap } from '../constants/http-code.contants'

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const response = ctx.getResponse<Response>()
    const status = exception.getStatus()

    const msg = HttpCodeMap[status] ?? exception.getResponse()['message'] ?? exception.message
    const code = exception.getStatus() ?? 999

    const errorResponse = returnPack({
      data: {},
      code,
      msg
    })

    response.status(status).header('Content-Type', 'application/json; charset=utf-8').json(errorResponse)
  }
}
